package com.softwinner.bt.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.ref.WeakReference;
import java.security.InvalidParameterException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.net.Uri;
import android.os.Gpio;
import com.softwinner.bt.BtApplication;
import com.softwinner.bt.CallDialog;
import com.softwinner.bt.InCallDialog;
import com.softwinner.bt.InComingDialog;
import com.softwinner.bt.MainActivity;

import com.softwinner.bt.R;
import com.softwinner.bt.bean.Record;
import com.softwinner.bt.policy.BTManager;
import com.softwinner.bt.util.BTConfig;
import com.softwinner.bt.util.BTLog;
import com.softwinner.bt.util.Command;
import com.softwinner.bt.util.DatabaseHelper;
import com.softwinner.bt.util.GpioHelper;
import com.softwinner.bt.util.LocationDBHelper;
import com.softwinner.bt.util.Utils;

import org.apache.http.util.EncodingUtils;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.app.Service;
import android.app.PendingIntent.CanceledException;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.os.SystemClock;
import android.util.Log;
import android.view.WindowManager;
import android.widget.Toast;
import android_serialport_api.SerialPort;

public class BtService extends Service{
	private static final String TAG="BtService";
	protected AudioManager mAudioManager;
	protected DatabaseHelper mDatabaseHelper;
	protected BTManager mBTManager;
	protected SerialPort mSerialPort;
    protected OutputStream mOutputStream;
    protected BufferedReader mBufferedReader;
    protected ReadThread mReadThread;
    LocationDBHelper addressDbHelper;
    private SharedPreferences mySharedPreferences;
    private static String KEY_FIRST = "first_start";
    private static String KEY_BTNAME = "bt_name";
    private boolean isFirstStart = true;
    
    public static int mBtStatus = -1;
	public static int mHFStatus = -1;
    public static String mBtName = "";
	public static String mBtPairName = "";
	public static String mBtPairAdd = "";
	
	private boolean isDownloadContacts = false;
	private boolean isPhoneComing = false;
	
	private static final int MSG_MUTE = 0;
	private static final int MSG_UNMUTE = 1;
	private static final int MSG_INSERT_CONTACTS=2;
	private static final int MSG_UPDATE_CONTACT_PROVIDER=3;
	private static final int MSG_SYNC_DEL_ALL_CONTACTS=4;
	String callNum;
	public static boolean isOutGoing=false;
	public static boolean isInComing=false;
	int calling=0;
	private int audioManager_volume=0;
	private boolean isBtPlay=false;
	private boolean al_tips=false;
	private Handler mHandler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			switch (msg.what) {
			case MSG_MUTE:
				setStreamMute(true);
				break;
			case MSG_UNMUTE:
				setStreamMute(false);
				break;
			case MSG_INSERT_CONTACTS:
				String cmd=msg.getData().getString("cmd");
				//mDatabaseHelper.insertSystemContact(cmd);
				//Log.i("zhu","mDatabaseHelper.insertContact(cmd)--and insertSystemContact------->"+mDatabaseHelper.insertContact(cmd));
				if (mDatabaseHelper.insertContact(cmd) == -1) {
	                return;
	            }
	            Utils.sendBroadcast(BtService.this, Utils.ACTION_UPDATE_CONTACTS);
				break;
			case MSG_UPDATE_CONTACT_PROVIDER:
				new Thread(
                        new Runnable(){
                            @Override
                            public void run() {
                            	try {
            	            		mDatabaseHelper.insertPhoneList();
            	            		Log.i(TAG,"wait insert contact apk list.size()===="+mDatabaseHelper.getSystemContacts().size());
            		            	mDatabaseHelper.BatchAddContact(mDatabaseHelper.getSystemContacts());
            					} catch (Exception e) {
            						Log.e(TAG,"insert contact provider apk error--->");
            					}
                            } 
                        }).start();
				break;
			case MSG_SYNC_DEL_ALL_CONTACTS:
				if(!al_tips){
					//playVideoWarnning();
					al_tips=true;
				}
				
				break;
				default:
				break;	
			}
		}
	};
	
	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}
	
	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		BTLog.i(this.getClass(), "onCreate");
		mySharedPreferences = getSharedPreferences("BtService", Activity.MODE_PRIVATE);
//		isFirstStart = mySharedPreferences.getBoolean(KEY_FIRST, true);
		mBtName = mySharedPreferences.getString(KEY_BTNAME, "");
//		BTLog.e(getClass(), "isFirstStart:"+isFirstStart+"   mBtName:"+mBtName);
		try {
			mDatabaseHelper = DatabaseHelper.getDatabaseHelper(this);
			mAudioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
			mBTManager = BTManager.getInstance();
			mSerialPort = BTManager.getSerialPort();
			mOutputStream = mSerialPort.getOutputStream();
	        mBufferedReader = mSerialPort.getBufferedReader();
	        addressDbHelper=new LocationDBHelper(this);
	        mReadThread = new ReadThread();
	        mReadThread.start();
		} catch (InvalidParameterException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
		IntentFilter filter = new IntentFilter();
		filter.addAction(Utils.ACTION_NAVI_CALL_ECAR);
		filter.addAction(Utils.AIOS_ANDROID_BT_GETBLTSTATUS);
		filter.addAction(Utils.AUDIOMANAGER_INTENT_ACTION_INTERRUPT_START);
		filter.addAction(Utils.AUDIOMANAGER_INTENT_ACTION_INTERRUPT_STOP);
		filter.addAction(Utils.AUDIOMANAGER_INTENT_ACTION_AIOS_START);
		filter.addAction(Utils.AUDIOMANAGER_INTENT_ACTION_AIOS_STOP);
		filter.addAction(Utils.AUDIOMANAGER_INTENT_ACTION_INSERT_START);
		filter.addAction(Utils.AUDIOMANAGER_INTENT_ACTION_INSERT_STOP);
		filter.addAction("audiomanager.intent.action.AIOS_MUSIC_PLAY");
		filter.addAction("audiomanager.intent.action.AIOS_MUSIC_PAUSE");
		filter.addAction("audiomanager.intent.action.VIDEO_PAUSE");
		filter.addAction("audiomanager.intent.action.VIDEO_PLAY");
		filter.addAction("audiomanager.intent.action.MUSIC_PAUSE");
		filter.addAction("audiomanager.intent.action.MUSIC_PLAY");
        registerReceiver(receiver, filter);
        
        //check HF status
        mBTManager.sendCommand(Command.SEND_CONNECT_STATUS);
        mBTManager.sendCommand(Command.SEND_QUERY_VOL+"22");//max 22
        Log.i(TAG, "oncreate to query val to 22------>");
       	 mBTManager.sendCommand(Command.SEND_VOICE_ECHO);
       	 mBTManager.sendCommand(Command.SEND_MIC_GAIN);
		mBTManager.sendCommand(Command.SEND_CLOSE_CALL_AUTO_ANSWER);
        if(mBtName.trim().equals("")){
        	mBTManager.sendCommand(Command.SEND_CHECK_ADDRESS);
        }        
	}
	
	private StringBuilder StringBuffer = new StringBuilder();
	int count =1;
	private class ReadThread extends Thread {
        @Override
        public synchronized void run() {
            super.run();
            while (!isInterrupted()) {
                try {	
                	int size;                	
					if (mBufferedReader == null) return;
					char[] buffer = new char[1024];
					size = mBufferedReader.read(buffer);
					if (size > 0) {	
						String command = new String(buffer, 0, size);
						StringBuffer.append(command);
						int index;
						while((index = StringBuffer.indexOf("\r\n"))!=-1) {
							String cmd = StringBuffer.substring(0,index);
							cmd = cmd.replace("\rn", "|rn|");
							cmd = cmd.replace("\r", "");
							cmd = cmd.replace("\n", "");
							/*if(cmd.startsWith("PB")){
								cmd = count + ". " + cmd;
								count++;
							}
							BTLog.e(getClass(), "===>" + cmd);*/
							onDataReceive(cmd);
							StringBuffer = StringBuffer.delete(0, index+"\r\n".length()-1);
						}
					}
                } catch (IOException e) {
                    e.printStackTrace();
                    return;
                }
            }
        }
    }
private void sendBtVolume(int volume){//int volume
	 Log.i("zhu_bt", "<><><>---蓝牙音乐audioManager_volume=="+audioManager_volume);
	 if(audioManager_volume<=0){
		 mBTManager.sendCommand(Command.SEND_QUERY_VOL+String.valueOf(volume));
	 }
 }
	
private boolean isPlayingBefore = false;
	private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Log.i(TAG,"<><><>---蓝牙音乐  广播监听---"+action + "audioManager_volume:" + audioManager_volume
            		 + "isBtPlay:" + isBtPlay + "isPlayingBefore:" + isPlayingBefore);
            if(Utils.ACTION_NAVI_CALL_ECAR.equals(action)){
				if (!CallDialog.isCall){
					startEcar();
				}
            }else if(Utils.AIOS_ANDROID_BT_GETBLTSTATUS.equals(action)){
            	/*接收到aios查询蓝牙连接广播，发送当前蓝牙连接状态给aios*/
            	if(mBtStatus == BTManager.STATE_CONNECTED){
            		Utils.sendBroadcast(BtService.this,BTConfig.BT_CONNECTED);
            	}else if(mBtStatus == BTManager.STATE_UNCONNECTION){
            		Utils.sendBroadcast(BtService.this,BTConfig.BT_DISCONNECTED);
            	}
            }else if("audiomanager.intent.action.MUSIC_PLAY".equals(action)
            		||"audiomanager.intent.action.AIOS_MUSIC_PLAY".equals(action)
                    ||"audiomanager.intent.action.VIDEO_PLAY".equals(action)){
            	if (isBtPlay) {
            		isPlayingBefore = true;
            	} else {
            		isPlayingBefore = false;
            	}
            	//sendBtVolume(0);
		mBTManager.sendCommand(Command.SEND_BT_MUSIC_PAUSE);
            	audioManager_volume++;
            }else if("audiomanager.intent.action.MUSIC_PAUSE".equals(action)
            		||"audiomanager.intent.action.AIOS_MUSIC_PAUSE".equals(action)
                    ||"audiomanager.intent.action.VIDEO_PAUSE".equals(action)){
            	if(audioManager_volume>0)audioManager_volume--;
            	if (isPlayingBefore) {
            		//sendBtVolume(16);
			mBTManager.sendCommand(Command.SEND_BT_MUSIC_PLAY);
            	}
            }else if(Utils.AUDIOMANAGER_INTENT_ACTION_INTERRUPT_START.equals(action) 
            		|| Utils.AUDIOMANAGER_INTENT_ACTION_AIOS_START.equals(action) 
            		|| Utils.AUDIOMANAGER_INTENT_ACTION_INSERT_START.equals(action)){
            	if (isBtPlay) {
            		isPlayingBefore = true;
            	} else {
            		isPlayingBefore = false;
            	}
            	//sendBtVolume(0);
		mBTManager.sendCommand(Command.SEND_BT_MUSIC_PAUSE);
            	audioManager_volume++;
            }else if(Utils.AUDIOMANAGER_INTENT_ACTION_INTERRUPT_STOP.equals(action) 
            		|| Utils.AUDIOMANAGER_INTENT_ACTION_AIOS_STOP.equals(action) 
            		|| Utils.AUDIOMANAGER_INTENT_ACTION_INSERT_STOP.equals(action)){
            	if(audioManager_volume>0)audioManager_volume--;
            	if (isPlayingBefore) {
            		//sendBtVolume(16);
			mBTManager.sendCommand(Command.SEND_BT_MUSIC_PLAY);
            	}
            	//mHandler.sendEmptyMessage(MSG_MUTE);
            	//Log.i("zhu_bt","GpioHelper.IsSpkOpen()----->"+GpioHelper.IsSpkOpen());
            	//修复播报结束蓝牙会发出papa声，假如是打开功放状态，就不做复位操作，关闭状态 ，就做复位操作
            	if(GpioHelper.IsSpkOpen()){
		            	Gpio.writeGpio('H', 15, 0);
		            	SystemClock.sleep(500);
		            	//Log.i("zhu_bt","close h15 and reopen after 500  seconds----->");
		            	//sendBtVolume(16);
		            	Gpio.writeGpio('H', 15, 1);
            	}
            }
        }
    };
    
    public void onDataReceive(String cmd){
//    	if(isFirstStart){
//    		isFirstStart = false;
//    		mySharedPreferences.edit().putBoolean(KEY_FIRST, false).commit();    				
//    	}
    	//BTLog.e(getClass(), "cmd = " + cmd);
    	//Log.i("zhu", "cmd=====" + cmd);
    	needMute(cmd);
    	/** NOT CONNECTED */
    	if(cmd.equals(Command.RECEIVE_NOT_CONNECTED)){
    		mBtStatus = BTManager.STATE_UNCONNECTION;
    		mBtPairName = "";
    		mBtPairAdd = "";
    		mHandler.sendEmptyMessage(MSG_UNMUTE);
    		//mHandler.sendEmptyMessage(MSG_SYNC_DEL_ALL_CONTACTS);
    		Utils.sendBroadcast(BtService.this, Utils.ACTION_BTSTATE_CHANGED);
    		BTConfig.sendBroadcast(BtService.this, BTConfig.BT_DISCONNECTED);
			Log.i(TAG, "send bt status unconnected--------->");
    		//reset bt power when not connected
    	}else if(cmd.equals(Command.RECEIVE_CONNECTED)){
    		/** CONNECTED */
		mBTManager.sendCommand(Command.SEND_QUERY_VOL+"22");//max 22
        	Log.i(TAG, "oncreate to query val to 22------>");
        	 mBTManager.sendCommand(Command.SEND_VOICE_ECHO);
         	mBTManager.sendCommand(Command.SEND_MIC_GAIN);
                mBTManager.sendCommand(Command.SEND_CLOSE_CALL_AUTO_ANSWER);
                mHandler.sendEmptyMessage(MSG_UNMUTE);//connected bt unmute
    		al_tips=false;
    		mBtStatus = BTManager.STATE_CONNECTED;
    		Utils.sendBroadcast(BtService.this,BTConfig.BT_CONNECTED);
			Log.i(TAG, "send bt status connected--------->");
    	}
    	/** Phone */
        else if(cmd.startsWith(Command.RECEIVE_START_OUTGOING)){
        	isOutGoing=true;
        	callNum = cmd.substring(2);
        	//Log.i("zhu","NewCallDialogisCall="+NewCallDialog.isCall+",,callNum==="+callNum);
        	if(!CallDialog.isCall)
        		try {
        			getPendingIntent(callNum,CallDialog.class);
        			Utils.sendBroadcast(BtService.this, "action.bt.AIOS_OUTGOING_RINGING",callNum,mDatabaseHelper.getNameByNum(callNum));					
				} catch (Exception e) {}
        		//Log.i("zhu","callDialog name="+mDatabaseHelper.getNameByNum(callNum)+",,callNum==="+callNum);
        		CallDialog.isCall=true;
        		if(callNum.equals("4008005005") 
						|| callNum.equals("075787807155")
						|| callNum.equals("4008015170")
						|| callNum.equals("075787807160")){				
		        		ComponentName componetName = new ComponentName("com.coagent.app",
		        				"com.coagent.server.EcarAppService");
						Intent ecar = new Intent();
						ecar.setComponent(componetName);
						stopService(ecar);
						startService(ecar);
		        	}
		        	mBTManager.sendCommand(Command.SEND_MIC_GAIN);
		        	try {
		        		addRecord(callNum,DatabaseHelper.TYPE_CALL);
					} catch (Exception e) {
						Log.e("zhu","add Record error--e"+e);
					}
       }else if(cmd.startsWith(Command.RECEIVE_START_INCOMING)){
    	   isInComing=true;
    	   mBTManager.sendCommand(Command.SEND_MIC_GAIN);
       	   mBTManager.sendCommand(Command.SEND_QUERY_VOL+"0");//"AT#VA" stop bt music when coming call
	   callNum = cmd.substring(2);
       	//BTLog.v(this.getClass(), "NewInComingDialog.isComing="+NewInComingDialog.isComing+",,,callNum==="+callNum);
       	if(!InComingDialog.isCall){
       		try {
       			getPendingIntent(callNum, InComingDialog.class);
       			Utils.sendBroadcast(BtService.this, "action.bt.AIOS_INCOMING_RINGING",callNum,mDatabaseHelper.getNameByNum(callNum));				
			} catch (Exception e) {}
       	}
       	Utils.sendBroadcast(this, Utils.ACTION_PHONE_COMING);
       	try {
       	//add record
       		addRecord(callNum,DatabaseHelper.TYPE_DIS);
		} catch (Exception e) {
			Log.e("zhu","add record error e"+e);
		}
       	isPhoneComing = true;
       }
		/** HFState */
		else if(cmd.startsWith(Command.RECEIVE_HF_STATUS)){
			if(cmd.length()>2){
				mHFStatus = Integer.parseInt(cmd.substring(2));
				if(mHFStatus==3){
					mBtStatus = BTManager.STATE_CONNECTED;
					mBTManager.sendCommand(Command.SEND_QUERY_PAIRE);
					BTConfig.sendBroadcast(this, BTConfig.BT_CONNECTED);
				}else if(mHFStatus==4){//电话拨出
					
				}else if(mHFStatus==5){//电话打入
				
				}else if(mHFStatus==6){//通话中
				//mBTManager.sendCommand("AT#VB");//unmute bt music when coming call
					//mAudioManager.requestAudioFocus(onAudioFocusChangeListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
					//Log.i("zhu","NewInCallDialog.isCalling="+NewInCallDialog.isCalling+",,callNum=="+callNum);        	
		        	if(!InCallDialog.isCall){
		        		InCallDialog.isCall = true;
		        		getPendingIntent(callNum, InCallDialog.class);
		        		mBTManager.sendCommand(Command.SEND_QUERY_VOL+"22");
		        	}
		        	try {
		        		if(isOutGoing){
		        			Utils.sendBroadcast(BtService.this, "action.bt.AIOS_OUTGOING_OFFHOOK",callNum,mDatabaseHelper.getNameByNum(callNum));
		        			//Log.i("zhu","callingDialog name="+mDatabaseHelper.getNameByNum(callNum)+",,callNum==="+callNum);
		        		}
		        		if(isInComing){
		        			Utils.sendBroadcast(BtService.this, "action.bt.AIOS_INCOMING_OFFHOOK",callNum,mDatabaseHelper.getNameByNum(callNum));
		        			//Log.i("zhu","comingDialog name="+mDatabaseHelper.getNameByNum(callNum)+",,callNum==="+callNum);
		        		}						
					} catch (Exception e) {
						Log.e("zhu","get Name faild"+e);
					}
				        	//add record
		        	try {
		        		  if(isPhoneComing){
					        isPhoneComing = false;
					        mDatabaseHelper.delTopRecord(callNum);
					        addRecord(callNum,DatabaseHelper.TYPE_COMING);
					       }
						}catch(Exception e) {
								Log.e("zhu","add Record error e"+e);
						}
				}
			}
		}
    	
    	/** CONNECTED */
    	/*else if(cmd.startsWith(Command.RECEIVE_START_CONNECT)){
    		String name;
    		String add;
            if (cmd.length() < 16) {
            	name="";
            	add="";
            }else{
            	if (cmd.substring(15, 16).equals("-")) {
                    name = cmd.substring(16, cmd.length());
                } else {
                    name = cmd.substring(15, cmd.length());
                }
            	add = cmd.substring(3, 15);
            }
            mBtPairName = name;
            mBtPairAdd = add;
    	}  
    	else if(cmd.equals(Command.RECEIVE_CONNECTED)){
    		mBtStatus = BTManager.STATE_CONNECTED;
    		mBTManager.sendCommand(Command.SEND_UPLOAD_CONTACTS);
    		Utils.sendBroadcast(this, Utils.ACTION_BTSTATE_CHANGED);
    	}*/
    	
    	/** HANGUP */
		else if (cmd.equals(Command.RECEIVE_HANGUP_PHONE)) {
			try {
				if(isOutGoing){
					Utils.sendBroadcast(BtService.this, "action.bt.AIOS_OUTGOING_IDLE",callNum,mDatabaseHelper.getNameByNum(callNum));
					isOutGoing=false;
				}
				if(isInComing){
					Utils.sendBroadcast(BtService.this, "action.bt.AIOS_INCOMING_IDLE",callNum,mDatabaseHelper.getNameByNum(callNum));
					isInComing=false;
				}				
			} catch (Exception e) {
				Log.e("zhu","get Name faild"+e);
			}
			Utils.sendBroadcast(this, Utils.ACTION_HANGUP);
			Intent i = new Intent(BTConfig.CALL_RECEIVE_ACTION);
			i.putExtra(BTConfig.ECAR_RECEICVER_CMD,
					BTConfig.CALL_STATUS_HAND_UP);
			sendBroadcast(i);
		}
    	
		/** DTMF */
		else if(cmd.startsWith(Command.RECEIVE_START_ECAR_DTMF)){
			String dtmfData = cmd.substring(cmd.length()-2, cmd.length()-1);
			Intent i = new Intent(BTConfig.CALL_RECEIVE_ACTION);
			i.putExtra(BTConfig.ECAR_RECEICVER_CMD, BTConfig.GOC_SEND_DTMF);
			i.putExtra(BTConfig.ECAR_REC_DTMF, dtmfData);
			sendBroadcast(i);
		}
    	
    	/** ADDRESS */
		else if(cmd.startsWith(Command.RECEIVE_START_BTADDRESS)){
			String address = cmd.substring(4);
			if(address.length()>3)
				address = address.substring(3);
			mBtName = " Car_" + address;
			mBTManager.sendCommand(Command.SEND_MODIFY_NAME + mBtName);
			mySharedPreferences.edit().putString(KEY_BTNAME, mBtName).commit();
			Utils.sendBroadcast(this, Utils.ACTION_GET_BTNAME);
		}
    	
    	/** UPLOAD CONTACTS AND RECORD */
    	else if (cmd.startsWith(Command.RECEIVE_START_UPLOAD_PHONEBOOK)) {
    			toInsertContact(cmd);
            //Log.i("zhu", "insertSystemContact==cmd==="+cmd);
        }else if (cmd.equals(Command.RECEIVE_UPLOAD_PHONEBOOK_END)) {
        	Utils.sendBroadcast(this, Utils.ACTION_FINISH_CONTACTS);
        	//insert into contact to contactProvider
        	Log.i(TAG, "send MSG_UPDATE_CONTACT_PROVIDER message to Handler cmd"+cmd);
        	mHandler.sendEmptyMessage(MSG_UPDATE_CONTACT_PROVIDER);
        }
        /*suzhen playing music*/
        else if(cmd.startsWith(Command.RECEIVE_PLAYING_MUSIC)){
        	//mAudioManager.requestAudioFocus(onAudioFocusChangeListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
        	if(!isBtPlay){
        		Utils.sendBroadcast(BtService.this,"audiomanager.intent.action.BT_MUSIC_PLAY");
            	isBtPlay=true;
            	Log.i(TAG,"<><><>---蓝牙音乐播放发送广播---audiomanager.intent.action.BT_MUSIC_PLAY");
            	//sendBtVolume(16);
        	}
        }else if(cmd.startsWith(Command.RECEIVE_PAUSE_MUSIC)){
        	/*ZHU pause bt music to play music*/
        	
        	if(isBtPlay){
        		Utils.sendBroadcast(BtService.this,"audiomanager.intent.action.BT_MUSIC_PAUSE");
        		Log.i(TAG,"<><><>---蓝牙音乐暂停发送广播---audiomanager.intent.action.BT_MUSIC_PAUSE");
        		isBtPlay=false;
        		//sendBtVolume(0);
        	}
        }
    	
    	/** Pair list */
        else if(cmd.startsWith(Command.RECEIVE_START_PAIR)){
        	if(cmd.startsWith("MX1")){
        		if(mBtPairName.trim().equals("")||mBtPairAdd.trim().equals("")){
        			String name;
            		String add;
                    if (cmd.length() < 16) {
                    	name="";
                    	add="";
                    }else{
                    	if (cmd.substring(15, 16).equals("-")) {
                            name = cmd.substring(16, cmd.length());
                        } else {
                            name = cmd.substring(15, cmd.length());
                        }
                    	add = cmd.substring(3, 15);
                    }
                    mBtPairName = name;
                    mBtPairAdd = add;
                    mBTManager.sendCommand(Command.SEND_UPLOAD_CONTACTS);
                    Utils.sendBroadcast(this, Utils.ACTION_BTSTATE_CHANGED);
        		}        		
        	}
        	BtApplication.addPairDevice(cmd);
        	Utils.sendBroadcast(this, Utils.ACTION_UPDATE_PAIRLIST);
        }
    }
    
    private void needMute(String cmd){
		if(BTManager.IsBtWifiCombo)	return;
    	if (cmd.equals(Command.RECEIVE_HF_STATUS_OUTGOING)//cmd.equals(Command.RECEIVE_HF_STATUS_INCOMING)||
				||cmd.equals(Command.RECEIVE_HF_STATUS_ONGOING)
				) {//||cmd.equals(Command.RECEIVE_START_INCOMING
			//mHandler.removeMessages(MSG_UNMUTE);
			mHandler.sendEmptyMessage(MSG_MUTE);
			Log.i("zhu","<><><>---蓝牙打电话中发送静音消息--------->");
		}else if (cmd.equals(Command.RECEIVE_HANGUP_PHONE)){	
			mHandler.sendEmptyMessage(MSG_UNMUTE);
			Log.i("zhu","<><><>---蓝牙挂断电话发送取消静音消息--------->");
		}
    }
    
    private synchronized void setStreamMute(boolean mute){
    	if(mAudioManager==null)
    		mAudioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
    	boolean currentMute = mAudioManager.isMasterMute();
    	BTLog.i(getClass(), "currentMute = " + currentMute + " mute = " + mute);
    	if(currentMute==mute){
    		return;
    	}
    	mAudioManager.setMasterMute(mute,0);
    }
    
    public void addRecord(String num,int type) throws Exception{
    	Record record = new Record();
    	record.setNumber(num);
    	if(mDatabaseHelper.getNameByNum(num)=="" || mDatabaseHelper.getNameByNum(num)==null){
    		record.setName(Utils.NameForNum(num));
    	}else{
    		record.setName(mDatabaseHelper.getNameByNum(num));
    	}
    	record.setType(type);
    	record.setAddress(addressDbHelper.findPhoneAreaByNumber(num)==null
    			?getString(R.string.no_record_address)
    			 :addressDbHelper.findPhoneAreaByNumber(num));
    	record.setTime(getNowTime());
    	long mRecordsize=mDatabaseHelper.insertRecord(record);
    	//Log.i("BtService", "address=="+addressDbHelper.findPhoneAreaByNumber(num)+",,,time==="+getNowTime()+",,,mRecordsize==="+mRecordsize);
    	Utils.sendBroadcast(this, Utils.ACTION_UPDATE_RECORDS);
    }
    private String getNowTime(){
    	SimpleDateFormat formatter=new SimpleDateFormat("MM:dd:HH:mm:ss");
    	Date curDate=new Date(System.currentTimeMillis());
    	return formatter.format(curDate);
    }
    /**
     * 
     * @param num
     * @param what 0:call ,1:calling,2:coming
     * @param cls
     */
    private void getPendingIntent(String num,Class<?> cls) {
    	Intent localIntent = new Intent();
        Bundle localBundle = new Bundle();
        localBundle.putString("phoneNum", num);
        localIntent.putExtras(localBundle);
        localIntent.setClass(this, cls);
        if(isBtAppTop()){
        	localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }else{
        	localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK);
        }
		 
		startActivity(localIntent);
    }
    
    public boolean isBtAppTop(){
    	ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
		RunningTaskInfo info = manager.getRunningTasks(1).get(0);
		String pkgName = info.topActivity.getPackageName();
		BTLog.v(getClass(), "isBtAppTop() topPkgName=" + pkgName);
		if (pkgName.equals("com.softwinner.bt")){
			return true;
		} 
		return false;
    }
    
    private void startEcar(){
    	if(!isHaveApp("com.coagent.app")){
    		Toast.makeText(this, R.string.ecar_not_install, 2000).show();
    		return;
    	}
    	Intent intent = new Intent();
        ComponentName cn = new ComponentName("com.coagent.app",
        		"com.coagent.activity.MainActivity");
    	intent.setComponent(cn);
    	intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
		startActivity(intent);
    }
    
    public boolean isHaveApp(String appPackagesName) {
        PackageManager pckMan = this.getPackageManager();
        List<PackageInfo> packs = pckMan.getInstalledPackages(0);
        for (int i = 0; i < packs.size(); i++) {
            if (packs.get(i).packageName.contains(appPackagesName)) {
                return true;
            }
        }
        return false;
    }
    public void toInsertContact(String cmd){
    	Message msg=new Message();
    	Bundle bun=new Bundle();
    	bun.putString("cmd", cmd);
		msg.setData(bun);
		msg.what=MSG_INSERT_CONTACTS;
		//Log.i("zhu", "sendMessage---------cmd-->"+cmd);
		mHandler.sendMessage(msg);
    }
	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		unregisterReceiver(receiver);
		//mAudioManager.abandonAudioFocus(onAudioFocusChangeListener);
		if(isBtPlay){
			Utils.sendBroadcast(BtService.this,"audiomanager.intent.action.BT_MUSIC_PAUSE");
		}
		mHandler.sendEmptyMessage(MSG_UNMUTE);
		mBTManager.closeSerialPort();
		super.onDestroy();
	}
}
